package com.micro.ai.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.template.entity.TemplateVersion;
import com.micro.ai.template.mapper.TemplateVersionMapper;
import com.micro.ai.template.service.TemplateVersionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模板版本Service实现
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateVersionServiceImpl extends ServiceImpl<TemplateVersionMapper, TemplateVersion>
        implements TemplateVersionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TemplateVersion createVersion(TemplateVersion templateVersion) {
        log.info("创建新版本, templateId: {}, version: {}", 
                templateVersion.getTemplateId(), templateVersion.getVersion());

        // 检查版本号是否已存在
        LambdaQueryWrapper<TemplateVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateVersion::getTemplateId, templateVersion.getTemplateId())
                .eq(TemplateVersion::getVersion, templateVersion.getVersion());
        
        if (this.count(wrapper) > 0) {
            throw new BusinessException("版本号已存在: " + templateVersion.getVersion());
        }

        // 设置创建时间
        templateVersion.setCreatedAt(LocalDateTime.now());
        
        // 如果是第一个版本，自动设置为活跃和稳定版本
        LambdaQueryWrapper<TemplateVersion> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(TemplateVersion::getTemplateId, templateVersion.getTemplateId());
        long versionCount = this.count(countWrapper);
        
        if (versionCount == 0) {
            templateVersion.setIsActive(true);
            templateVersion.setIsStable(true);
        } else {
            templateVersion.setIsActive(false);
            templateVersion.setIsStable(false);
        }

        this.save(templateVersion);
        log.info("版本创建成功, versionId: {}", templateVersion.getId());
        
        return templateVersion;
    }

    @Override
    public IPage<TemplateVersion> getVersionsByTemplateId(String templateId, Page<TemplateVersion> page) {
        LambdaQueryWrapper<TemplateVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateVersion::getTemplateId, templateId)
                .orderByDesc(TemplateVersion::getCreatedAt);
        
        return this.page(page, wrapper);
    }

    @Override
    public TemplateVersion getActiveVersion(String templateId) {
        LambdaQueryWrapper<TemplateVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateVersion::getTemplateId, templateId)
                .eq(TemplateVersion::getIsActive, true);
        
        TemplateVersion version = this.getOne(wrapper);
        if (version == null) {
            log.warn("未找到活跃版本, templateId: {}", templateId);
            throw new BusinessException("未找到活跃版本");
        }
        
        return version;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void activateVersion(String versionId) {
        log.info("激活版本, versionId: {}", versionId);

        TemplateVersion version = this.getById(versionId);
        if (version == null) {
            throw new BusinessException("版本不存在");
        }

        // 取消同一模板的其他活跃版本
        LambdaQueryWrapper<TemplateVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateVersion::getTemplateId, version.getTemplateId())
                .ne(TemplateVersion::getId, versionId);
        
        List<TemplateVersion> otherVersions = this.list(wrapper);
        for (TemplateVersion otherVersion : otherVersions) {
            otherVersion.setIsActive(false);
        }
        this.updateBatchById(otherVersions);

        // 激活当前版本
        version.setIsActive(true);
        this.updateById(version);
        
        log.info("版本激活成功, versionId: {}", versionId);
    }

    @Override
    public List<TemplateVersion> getStableVersions(String templateId) {
        LambdaQueryWrapper<TemplateVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateVersion::getTemplateId, templateId)
                .eq(TemplateVersion::getIsStable, true)
                .orderByDesc(TemplateVersion::getCreatedAt);
        
        return this.list(wrapper);
    }

    @Override
    public Object compareVersions(String versionId1, String versionId2) {
        TemplateVersion version1 = this.getById(versionId1);
        TemplateVersion version2 = this.getById(versionId2);

        if (version1 == null || version2 == null) {
            throw new BusinessException("版本不存在");
        }

        Map<String, Object> comparison = new HashMap<>();
        comparison.put("version1", version1);
        comparison.put("version2", version2);
        
        // 比较关键字段
        Map<String, Object> differences = new HashMap<>();
        differences.put("versionNumber", Map.of("v1", version1.getVersion(), "v2", version2.getVersion()));
        differences.put("promptChanged", !version1.getBasePromptTemplate().equals(version2.getBasePromptTemplate()));
        differences.put("schemaChanged", !version1.getInputSchema().equals(version2.getInputSchema()));
        
        comparison.put("differences", differences);
        
        return comparison;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rollbackToVersion(String templateId, String versionId) {
        log.info("回滚到版本, templateId: {}, versionId: {}", templateId, versionId);

        TemplateVersion targetVersion = this.getById(versionId);
        if (targetVersion == null || !targetVersion.getTemplateId().equals(templateId)) {
            throw new BusinessException("目标版本不存在或不属于该模板");
        }

        // 激活目标版本
        this.activateVersion(versionId);
        
        log.info("回滚成功, templateId: {}, versionId: {}", templateId, versionId);
    }
}

